#include "vtor_deque.h"

#ifdef __VTOR_DEQUE__


// 假设溢出处理函数，这里简单打印提示信息
void VtorDeque_OverflowCallback(VtorDeque* que)
{
    printf("Overflow occurred in VtorDeque!\n");
}

// 将输入缓冲区的数据从尾部插入 VtorDeque
void VtorDeque_PushBufBack(VtorDeque* que, uint8_t* inBuf, int16_t inLen)
{
    // 每次push，只触发一次overflow回调
    uint8_t overFlag = 0;
    for (int i = 0; i < inLen; i++)
    {
        if (que->charCnt == que->bufSize)
        {
            // 缓冲区已满，覆盖最旧的数据
            que->frontIdx++;
            que->frontIdx %= que->bufSize;
            que->charCnt--;
            if (0 == overFlag)
            {
                overFlag = 1;
                VtorDeque_OverflowCallback(que);
            }
        }
        // 塞入数据
        que->buf[que->backIdx++] = inBuf[i];
        que->backIdx %= que->bufSize;
        que->charCnt++;
    }
}

// 从头部弹出数据到输出缓冲区
int16_t VtorDeque_PopBufFront(VtorDeque* que, uint8_t* outBuf, int16_t expOutLen)
{
    int16_t actualOutLen = 0;
    // 取 缓冲区内元素个数  期望输出元素个数    的较小值
    expOutLen = expOutLen < que->charCnt ? expOutLen : que->charCnt;
    while (actualOutLen < expOutLen)
    {
        outBuf[actualOutLen++] = que->buf[que->frontIdx++];
        que->frontIdx %= que->bufSize;
        que->charCnt--;
    }
    return actualOutLen;
}

// 从头部弹出一行数据到输出缓冲区，遇到 '\n' 结束，并在字符串后追加 '\0'
int16_t VtorDeque_PopLineFront(VtorDeque* que, uint8_t* outBuf, int16_t expOutLen)
{
    int16_t actualOutLen = 0;
    expOutLen = expOutLen < que->charCnt ? expOutLen : que->charCnt;
    while (actualOutLen < expOutLen)
    {
        outBuf[actualOutLen++] = que->buf[que->frontIdx++];
        que->frontIdx %= que->bufSize;
        que->charCnt--;

        if (outBuf[actualOutLen-1] == '\n')
        {
            break;
        }
    }
    // 在字符串末尾追加 '\0'
    outBuf[actualOutLen] = '\0';
    return actualOutLen;
}
#endif // __VTOR_DEQUE__

